/**
 * Created by levy on 16/6/20.
 */
import {shopping} from "../const/shopping.js";
import PullRefresh from "../components/mui/PullRefresh.js";
import NoData from "../components/NoData.js";
import Img from "../components/Img";
import Cart from "../components/shopping/Cart";

const lf = liefeng,
    R = React,
    RC = React.createClass,
    log = lf.utils.log,
    ajax = lf.utils.ajax;

const categoryId = lf.utils.getUrlParam('categoryId');


/**
 * props:
 *    page
 */
const Root = RC({
    getInitialState() {
        return {
            itemList: [],
            total: 1,
        }
    },
    getList(page) {
        let me = this;
        ajax({
            data: {
                currPage: page,
                size: 6,
                categoryId: categoryId
            },
            url: shopping.api.prefix + shopping.api.itemList,
            success(data) {
                if (data.code != 200) alert('没有获取到数据');
                else {

                    if (!data.dataList.length) {
                        me.setState({
                            total: 0
                        })
                    }
                    else {
                        let itemList = me.state.itemList;
                        itemList.push(...data.dataList);//ES6 合并数组新写法

                        mui('#pullrefresh')
                            .pullRefresh()
                            .endPullupToRefresh((itemList.length == data.maxCount)); //refresh completed

                        me.setState({
                            itemList: itemList
                        })
                    }

                }
            }
        });
    },
    componentWillMount() {
        this.getList(1);
    },
    componentWillReceiveProps: function (nextProps) {
        this.getList(nextProps.page);
    },
    render() {
        if (!this.state.total)
            return <NoData data={{span_text:"商品已被抢空啦！"}}/>;

        let itemList = lf.utils.to2DArray(this.state.itemList, 2).map((array, i) => {
            return (
                <div key={'array-'+ i} className="flex space-between">
                    {array.map((item, i)=> {
                        return (
                            <div key={'item-'+i} className="img-box" data-id={item.goodsId} data-name={item.goodsName}>
                                <Img style={{height:180}}
                                     src={lf.utils.getProtocol() + shopping.imgPre + item.goodsThumb}/>
                                <p className="item-name">{item.goodsName}</p>
                                <div className="price-wrapper flex space-between">
                                    <div className="price-info">
                                            <span className="sale-price num">{"￥" + (item.promotePrice > 0 ?
                                                item.promotePrice : item.shopPrice)}</span>
                                        <span className="origin-price num">{"￥" + item.marketPrice}</span>
                                    </div>
                                </div>
                            </div>
                        )
                    })}
                </div>
            )
        });
        return <div className="shopping item-list" ref="list">
            {itemList}
        </div>
    },
    componentDidUpdate() {
        $(R.findDOMNode(this.refs.list)).find('.img-box').off().on('tap', function () {
            let $me = $(this),
                id = $me.data('id'),
                name = $me.data('name');

            lf.bridgeJs.doAction(`shopping-item-detail.html?goodsId=${id}`, name);
        });
    },
});

const PullRefreshCon = RC({
    getInitialState() {
        return {
            page: 1,
        }
    },
    pullupFn: function () {
        let newPage = ++this.state.page;
        this.setState({page: newPage});
    },
    render() {
        return <PullRefresh pullupFn={this.pullupFn} data={<Root page={this.state.page}/>}/>;
    }
});

const CartContainer = RC({
    getInitialState() {
        return {
            cartNum: 0,
        }
    },
    getCartNum(user) {
        ajax({
            url: shopping.api.prefix + shopping.api.cart.getGoodsNum,
            data: {
                custGlobalId: user.globalId || (user.custLoginVo && user.custLoginVo.globalId),
            },
            success: function (data) {
                this.setState({cartNum: data.data});
            }.bind(this)
        });
    },
    componentWillMount() {
        let me = this;

        lf.appJs.getUser((user) => {
            me.getCartNum(user);
        });

        lf.appJs.refresh((user) => {
            me.getCartNum(user);
        });
    },
    render() {
        return <Cart num={this.state.cartNum}/>
    }
});


R.render(<div>
    <PullRefreshCon/>
    <CartContainer/>
</div>, document.getElementById('root'), function () {
    $('.mui-scroll').css({backgroundColor: '#f2f2f2'});
});

